﻿using MediatR;
using TaskProject.Application.Command.Production;
using TaskProject.Domain.Production;
using TaskProject.ErrorCode;
using TaskProject.Extension;
using TaskProject.InfrasIntructure.Interface;

namespace TaskProject.Application.Handler.Production
{
    public class GetWorkOrderOneHandler : IRequestHandler<GetWorkOrderOneCommand, APIResult<WorkOrderDTO>>
    {
        IBaseRepository<WorkorderModel> workRepo;
        private readonly IBaseRepository<LeaderModel> leaderRepo;
        private readonly IBaseRepository<ProductItemModel> productRepo;

        public GetWorkOrderOneHandler(IBaseRepository<WorkorderModel> workRepo, IBaseRepository<LeaderModel> leaderRepo, IBaseRepository<ProductItemModel> productRepo)
        {
            this.workRepo = workRepo;
            this.leaderRepo = leaderRepo;
            this.productRepo = productRepo;
        }
        public Task<APIResult<WorkOrderDTO>> Handle(GetWorkOrderOneCommand request, CancellationToken cancellationToken)
        {
            APIResult<WorkOrderDTO> res = new APIResult<WorkOrderDTO>();
            var works = workRepo.GetAll().Where(c=>c.WorkOrderId==request.WorkOrderId);
            var leader = leaderRepo.GetAll();
            var product = productRepo.GetAll();
            var list = from a in works
                       join b in leader
                       on a.LeaderId equals b.LeaderId
                       join c in product
                       on a.ProductId equals c.ProductId

                       select new WorkOrderDTO
                       {
                           WorkOrderId = a.WorkOrderId,
                           WorkOrderCode = a.WorkOrderCode,
                           WorkOrderName = a.WorkOrderName,
                        
                           LeaderId = a.LeaderId,
                           LeaderName = b.LeaderName,
                           OrderNum = a.OrderNum,
                           WorderOrderDesc = a.WorderOrderDesc,
                           WorkOrderDate = a.WorkOrderDate,
                           ProductId = a.ProductId,
                           ProductName = c.ProductName,
                           ProductCode = c.ProductCode,
                           Classify=c.Classify,
                           Specification=c.Specification,
                           UnitName=c.UnitName,
                           PlanStart=c.PlanStart,
                           PlanEnd=c.PlanEnd,
                           PlanNum=c.PlanNum,
                       };

            res.Msg = "查询生产工单成功";
            res.Code = APIEnum.Success;
            res.Data = list.FirstOrDefault();
            return Task.FromResult(res);
        }
    }
}
